/********************************************************************
	created:	2012/02/03
	filename: 	FreeFlyCamera.cpp
	author:		Mwolf
	
	purpose:	
*********************************************************************/

#include "stdafx.h"

#include "FreeFlyCamera.h"

FreeFlyCamera::FreeFlyCamera()
: m_Yaw(0.f), m_Pitch(0.f),
  m_Position(0.f, 0.f, 0.f)
{
	m_RotMatrix = Matrix4::IDENTITY;
}

void FreeFlyCamera::SetupView()
{

	m_RotMatrix = Matrix4::BuildRotationMatrix(m_Pitch, ROTATION_AXIS_X) *
				  Matrix4::BuildRotationMatrix(m_Yaw, ROTATION_AXIS_Y);

	Matrix4 viewMat;
	viewMat = m_RotMatrix *
			  Matrix4::BuildTranslationMatrix( m_Position );
	viewMat = viewMat.InverseMatrix();
	RenderSystem::SetViewMatrix( viewMat );
}

Ray FreeFlyCamera::GetCameraRay( float x, float y, float dist ) const
{
	Matrix4 matProj = RenderSystem::GetProjectionMatrix();
	Matrix4 matView = RenderSystem::GetViewMatrix();
	Ray ray;

	Vector3 v = Vector3((2.f * x - 1.f) / matProj.m11, - (2.f * y - 1.f) / matProj.m22, 1.f);

	Matrix4 m = matView.InverseMatrix();

	ray.dir.x = v.x * m.m11 + v.y * m.m21 + v.z * m.m31;
	ray.dir.y = v.x * m.m12 + v.y * m.m22 + v.z * m.m32;
	ray.dir.z = v.x * m.m13 + v.y * m.m23 + v.z * m.m33;
	ray.origin.x = m.m41;
	ray.origin.y = m.m42;
	ray.origin.z = m.m43;

	ray.dist = dist;
	ray.dir.Normalize();

	return ray;
}

void FreeFlyCamera::Translate( const Vector3& vec )
{
	m_Position += Vec3_Transform(vec, m_RotMatrix);
}

void FreeFlyCamera::ModifyYaw( float val )
{
	m_Yaw += val;
}

void FreeFlyCamera::ModifyPitch( float val )
{
	m_Pitch += val;
}
